<template>
  <div class="supply-product-management">
    <div class="header">
      <h2>供货商品管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        新增商品
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="商品名称/编号/型号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table 
      v-loading="loading" 
      :data="tableData" 
      style="width: 100%"
      stripe
    >
      <el-table-column prop="productName" label="商品名称" min-width="120" />
      <el-table-column prop="productCode" label="商品编号" width="120" />
      <el-table-column prop="model" label="型号" width="100" />
      <el-table-column prop="cost" label="成本" width="80">
        <template #default="scope">
          ¥{{ scope.row.cost }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="余量" width="80" />
      <el-table-column label="图片" width="80">
        <template #default="scope">
          <img 
            v-if="scope.row.image" 
            :src="getImageUrl(scope.row.image)" 
            class="table-image"
            @error="handleImageError"
          />
          <span v-else class="no-image">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="supplierName" label="供货公司" min-width="120" />
      <el-table-column prop="categoryName" label="分类" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="showEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @closed="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品编号" v-if="isEdit">
          <el-input v-model="form.productCode" readonly>
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            商品编号在创建时自动生成，不可修改
          </div>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="成本" prop="cost">
          <el-input-number
            v-model="form.cost"
            :precision="2"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="余量" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="供货公司" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择供货公司" style="width: 100%">
            <el-option
              v-for="company in companies"
              :key="company.id"
              :label="company.companyName"
              :value="company.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="image-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :on-error="handleImageError"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="getImageUrl(form.image)" class="uploaded-image" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="image-tips">
            <p>支持 jpg、png、gif 格式，文件大小不超过 5MB</p>
            <el-button v-if="form.image" @click="removeImage" type="danger" size="small" plain>删除图片</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Key, InfoFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const editId = ref(null)
const formRef = ref()
const companies = ref([])
const categories = ref([])
const imageUploading = ref(false)

// 文件上传配置
const uploadAction = ref('/api/upload/image')
const uploadHeaders = ref({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
})

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  productName: '',
  productCode: '',
  model: '',
  cost: null,
  stock: 0,
  supplierId: null,
  categoryId: null,
  image: ''
})

// 表单验证规则
const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  cost: [
    { required: true, message: '请输入成本', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择供货公司', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑商品' : '新增商品')

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const response = await request.get('/supply-product/page', {
      params: {
        page: pagination.current,
        size: pagination.size,
        keyword: searchForm.keyword
      }
    })
    
    // 使用封装的request后，成功的响应直接返回Result对象
    const pageData = response.data
    tableData.value = pageData?.records || []
    pagination.total = pageData?.total || 0
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取供货公司列表
const getCompanies = async () => {
  try {
    const response = await request.get('/supply-product/companies')
    companies.value = response.data || []
  } catch (error) {
    console.error('获取供货公司失败:', error)
    companies.value = []
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const response = await request.get('/supply-product/categories')
    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类失败:', error)
    categories.value = []
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  pagination.current = 1
  getTableData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getTableData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getTableData()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  editId.value = null
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEdit.value = true
  editId.value = row.id
  Object.assign(form, {
    productName: row.productName,
    productCode: row.productCode,
    model: row.model,
    cost: row.cost,
    stock: row.stock,
    supplierId: row.supplierId,
    categoryId: row.categoryId,
    image: row.image
  })
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 新增时不需要重置商品编号，因为它是自动生成的
  const resetData = {
    productName: '',
    model: '',
    cost: null,
    stock: 0,
    supplierId: null,
    categoryId: null,
    image: ''
  }
  
  // 编辑时保留商品编号
  if (!isEdit.value) {
    resetData.productCode = ''
  }
  
  Object.assign(form, resetData)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const url = isEdit.value 
      ? `/supply-product/${editId.value}` 
      : '/supply-product'
    const method = isEdit.value ? 'put' : 'post'
    
    await request[method](url, form)
    
    ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    if (error.name === 'ValidationError') {
      return
    }
    console.error('操作失败:', error)
    // 错误信息已经在request拦截器中处理了
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${row.productName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/supply-product/${row.id}`)
    
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      // 错误信息已经在request拦截器中处理了
    }
  }
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传 JPG、PNG、GIF 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  
  imageUploading.value = true
  return true
}

// 图片上传成功
const handleImageSuccess = (response) => {
  imageUploading.value = false
  if (response.code === 200) {
    // MinIO返回的数据结构，使用fileUrl作为图片地址
    form.image = response.data?.fileUrl || response.data?.filePath || ''
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 图片上传失败
const handleImageError = (error) => {
  imageUploading.value = false
  ElMessage.error('图片上传失败')
  console.error('Upload error:', error)
}

// 删除图片
const removeImage = async () => {
  if (!form.image) return
  
  try {
    // 直接传递图片路径或URL，后端会处理URL解析
    await request.delete('/upload/image', {
      params: { filePath: form.image }
    })
    form.image = ''
    ElMessage.success('图片删除成功')
  } catch (error) {
    // 即使删除失败也清空显示
    form.image = ''
    console.error('Delete image error:', error)
  }
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  // 如果是完整URL直接返回（MinIO的URL）
  if (imagePath.startsWith('http')) {
    return imagePath
  }
  // 兼容旧的本地路径格式
  const cleanPath = imagePath.startsWith('/') ? imagePath.substring(1) : imagePath
  return `/uploads/${cleanPath}`
}

// 页面挂载时加载数据
onMounted(() => {
  console.log('SupplyProductManagement 组件已挂载，开始加载数据...')
  getTableData()
  getCompanies()
  getCategories()
})
</script>

<style scoped>
.supply-product-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 图片上传样式 */
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  display: block;
}

.uploaded-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  display: block;
}

.image-tips {
  margin-top: 8px;
}

.image-tips p {
  margin: 5px 0;
  color: #909399;
  font-size: 12px;
}

.form-tip {
  margin-top: 5px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 4px;
  color: #1e40af;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.form-tip .el-icon {
  color: #3b82f6;
}

/* 表格中的图片 */
.table-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.no-image {
  color: #909399;
  font-size: 12px;
}
</style> 